package com.bsj.travel.process.handle.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bsj.consumerQ.function.HandleRun;
import com.bsj.travel.constant.TdEngineDataConstants;
import com.bsj.travel.def.common.DTO.tdengine.TDLogDto;
import com.bsj.travel.def.monitor.CloudLog;
import com.bsj.travel.mapper.tdengine.TableTDengineMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author yinhao
 * @version 1.0
 * @description 时序存储实现类
 * @date 2024/2/18
 */
@Service
@Slf4j
public class DefaultTdEngineHandleRun implements HandleRun {

    @Resource
    private TableTDengineMapper tDengineMapper;

    @Override
    public void doRun(List<byte[]> list) {
        //尽可能一次写入多条数据
//        Map<String, List<TDLogDto>> map = new HashMap<>();

        List<TDLogDto> tdLogDtos = new ArrayList<>();
        for (byte[] bytes: list) {
            String message = new String(bytes);
            CloudLog cloudLog = JSON.parseObject(message, CloudLog.class);
            //deviceName&productKey
            String identify = cloudLog.getIdentify();
            String[] split = identify.split("&");
            String deviceName = split[0];
            String productKey = split[1];
//            List<TDLogDto> tdLogDtos = map.get(productKey);
//            if (tdLogDtos == null) {
//                tdLogDtos = new ArrayList<>();
//            }
            TDLogDto td = new TDLogDto();
            String superTableName = TdEngineDataConstants.T_LOG + productKey;
            td.setSuperTableName(superTableName);
            td.setTableName(superTableName + "_" + deviceName);
            td.setCode(cloudLog.getCode());
            td.setTs(cloudLog.getTs());
            td.setTraceId(cloudLog.getTraceId());
            if (cloudLog.getContent() != null && cloudLog.getContent().trim().length() < 32768) {
                //内容过长不做存储,规定内容必须少于64kb
                td.setContent(cloudLog.getContent().trim());
            }
            td.setServeType(cloudLog.getServeType());
            td.setOperate(cloudLog.getOperate());
            td.setIdentify(cloudLog.getIdentify());
            td.setCode(cloudLog.getCode());
            tdLogDtos.add(td);
//            map.put(productKey, tdLogDtos);

        }
//        if (!map.isEmpty()) {
//            Iterator<Map.Entry<String, List<TDLogDto>>> iterator = map.entrySet().iterator();
//            while (iterator.hasNext()) {
//                Map.Entry<String, List<TDLogDto>> next = iterator.next();
//                List<TDLogDto> value = next.getValue();
//                tDengineMapper.insertBatchData(value);
//            }
//        }

        if (!tdLogDtos.isEmpty()) {
            tDengineMapper.insertBatchData(tdLogDtos);
        }
    }
}
